//返回地址字符串 ，以备获取经纬度
let setFreightAddress = ()=>{
    let province = $("#province").val()?$("#province").val():"";
    let city = $("#city").val() ? $("#city").val():"" ;
    let county = $("#county").val() ? $("#county").val():"" ;
    let detail = $("#detail").val() ? $("#detail").val() : "";
    return province+city+county+detail
};

//表单验证
let nc_base = new NiceValidate([
    {dom:document.getElementById("name")},
    {dom:document.getElementById("is_free")},
    {dom:document.getElementById("province"),isNull:true},
    {dom:document.getElementById("city"),isNull:true},
    {dom:document.getElementById("county"),isNull:true},
    {dom:document.getElementById("detail"),isNull:true},
]);
let nc_local = new NiceValidate([
    {dom:document.getElementById("transport")},
    {dom:document.getElementById("BaseKM")},
    {dom:document.getElementById("price")},
    {dom:document.getElementById("maxKM"),isNull:true},
    {dom:document.getElementById("perKM"),isNull:true},
    {dom:document.getElementById("KMPrice")},
]);

//添加运费模板数据
let addFreight = (data)=>{
    $.post(rootPath+"/freight",data,function (res) {
        if(res.meta.code ===200){
            setStatus.setEnable($("#submit"),"提交");
            alert("添加成功")
        }else {
            alert("添加失败--"+res.meta.code)
        }
    })
};

//点击按钮获取经纬度并提交请求
$("#submit").click(function(){
    AMap.service('AMap.Geocoder',function(){//回调函数
        let geocoder = new AMap.Geocoder();
        geocoder.getLocation(setFreightAddress(), function(status, result) {
            let freight_data = nc_base.niceValidate();
            let freight_data_local = nc_local.niceValidate();
            if (status === 'complete' && result.info === 'OK' && freight_data && freight_data_local) {
                setStatus.setDisable($("#submit"));
                freight_data.local_json = JSON.stringify(freight_data_local);
                freight_data.position = result.geocodes[0].location.lng+","+result.geocodes[0].location.lat;
                //提交请求
                addFreight(freight_data)
            }else{
                alert("您填写的信息有误")
            }
        });
    })
});
